//防抖如果用户多次频繁操作以最后一次为准，当然也可以以第一次为准，进行数据更新或者网络资源请求，以消除冗余的操作，或者减少一定的请求资源浪费
export function debounce(fn, delay) {
    let timeout = null;
    return function () {
        let context = this, args = arguments;
        clearTimeout(timeout);
        let callNow = !timeout;
        timeout = setTimeout(() => {
            timeout = null;
        }, delay);
        if (callNow) fn.apply(context, args);
    };
}


//判断当前设备是否为移动设备
export function isMobile() {
    return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
}
//生成指定长度字符串
export function getRandomString(length) {
    let result = '';
    const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    const charactersLength = characters.length;
    for (let i = 0; i < length; i++) {
        result += characters.charAt(Math.floor(Math.random() * charactersLength));
    }
    return result;
}
//生成uuid:"a1ca0f7b-51bd-4bf3-a5d5-6a74f6adc1c7"
export function guid() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = Math.random() * 16 | 0,
            v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}

//添加缓存(过期时间)
export function setCacheWithExpiry(key, value, ttl) {
    const item = {
        value: value,
        expiry: Date.now() + ttl,
    };
    sessionStorage.setItem(key, JSON.stringify(item));
}
//获取缓存(过期时间)
export function getCacheWithExpiry(key) {
    const itemStr = sessionStorage.getItem(key);
    if (!itemStr) {
        return null;
    }
    const item = JSON.parse(itemStr);
    if (Date.now() > item.expiry) {
        sessionStorage.removeItem(key); // 清除过期数据
        return null;
    }
    return item.value;
}